package tencent

import (
	"anban/utils"
	"crypto/tls"
	"encoding/json"
	"fmt"
	"github.com/astaxie/beego"
	"io/ioutil"
	"net/http"
	"strings"
	"time"
)

// 语音消息

type VoiceMsgTel struct {
	Mobile     string `json:"mobile"`     // 电话号码
	NationCode string `json:"nationcode"` // 国家码，中国86
}

type VoiceMsg struct {
	TplId  int64       `json:"tpl_id"` // 模板id
	Params []string    `json:"params"` // 模板参数
	Sig    string      `json:"sig"`    // 签名
	Tel    VoiceMsgTel `json:"tel"`
	Time   int64       `json:"time"` // 当前时间戳
}

type VoiceMsgRes struct {
	Result int    `json:"result"`
	ErrMsg string `json:"errmsg"`
	CallId string `json:"callid"`
	Ext    string `json:"ext"`
}

func NewVoiceMsg(tplId int64, mobile string, params []string) *VoiceMsg {
	return &VoiceMsg{
		TplId:  tplId,
		Params: params,
		Sig:    "",
		Tel: VoiceMsgTel{
			Mobile:     mobile,
			NationCode: "86",
		},
		Time: 0,
	}
}

func (v *VoiceMsg) Send() (*VoiceMsgRes, error) {
	appId := beego.AppConfig.String("vmsappid")
	appKey := beego.AppConfig.String("vmsappkey")
	randomStr := utils.GetRandomString(10)

	curTime := time.Now().Unix()
	sigStr := fmt.Sprintf("appkey=%s&random=%s&time=%d&mobile=%s", appKey, randomStr, curTime, v.Tel.Mobile)
	sig := utils.GetSHA256HashCode(sigStr)
	v.Sig = sig
	v.Time = curTime

	url := fmt.Sprintf("https://cloud.tim.qq.com/v5/tlsvoicesvr/sendtvoice?sdkappid=%s&random=%s", appId, randomStr)

	content, err := json.Marshal(v)
	if err != nil {
		return nil, utils.NewError(0, fmt.Sprintf("无法解析语音消息结构体:%s", err.Error()))
	}
	contentStr := string(content)

	req, _ := http.NewRequest("POST", url, strings.NewReader(contentStr))
	req.Header.Set("Content-Type", "application/x-www-form-urlencoded")

	tr := &http.Transport{
		TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
	}
	client := &http.Client{Transport: tr}

	resp, err := client.Do(req)
	if err != nil {
		return nil, utils.NewError(0, fmt.Sprintf("发送语音消息请求失败:%s", err.Error()))
	}
	defer resp.Body.Close()

	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return nil, utils.NewError(0, fmt.Sprintf("发送语音消息请求成功，但无法读取返回的结果:%s", err.Error()))
	}

	voiceMsgRes := VoiceMsgRes{}
	err = json.Unmarshal(body, &voiceMsgRes)
	if err != nil {
		return nil, utils.NewError(0, fmt.Sprintf("发送语音消息请求成功，但返回的结果无法解析为结构体:%s", err.Error()))
	}

	if voiceMsgRes.Result != 0 {
		return &voiceMsgRes, utils.NewError(0, fmt.Sprintf("发送语音消息发送失败:%s", voiceMsgRes.ErrMsg))
	}

	return &voiceMsgRes, nil
}
